package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.dubbo.mappers.UserConclusionMapper;
import com.tanhua.model.domain.UserConclusion;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

@DubboService
public class UserConclusionApiImpl implements UserConclusionApi {
    @Autowired
    private UserConclusionMapper userConclusionMapper;

    //保存或更新
    @Override
    public void updateOrSave(UserConclusion userConclusion) {
        if (userConclusion == null) {
            throw new RuntimeException("用户类型保存失败,userConclusion对象为空");
        }
        //判断是否存在
        Long userId = userConclusion.getUserId();
        LambdaQueryWrapper<UserConclusion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, UserConclusion::getUserId, userId);
        UserConclusion find = userConclusionMapper.selectOne(wrapper);
        userConclusion.setCreated(LocalDateTime.now());
        if (find == null) {
            //数据库没有则保存
            //userConclusionMapper.insert(userConclusion);
            userConclusionMapper.save(userConclusion);
        } else {
            //数据库有则更新
            userConclusionMapper.update(userConclusion, wrapper);
        }
    }

    /**
     * 查十个对象
     *
     * @param conclusion
     * @return
     */
    @Override
    public List<UserConclusion> findTenUserConclusionByConclusion(String conclusion) {

        LambdaQueryWrapper<UserConclusion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(conclusion != null, UserConclusion::getConclusion, conclusion);
        // TODO: 2022/1/9 需要设置返回总人数为10
        List<UserConclusion> userConclusions = userConclusionMapper.selectList(wrapper);
        return userConclusions;
    }

    @Override
    public UserConclusion findUserLevelByUserId(Long userId) {
        LambdaQueryWrapper<UserConclusion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, UserConclusion::getUserId, userId);
        UserConclusion userConclusion = userConclusionMapper.selectOne(wrapper);
        return userConclusion;
    }
}
